package com.chinatelecom.clientservice.pojo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TreeMenu {

	private List<BaseMenu> menuList;
	private BaseMenu root;

	public TreeMenu(List<BaseMenu> menuList) {
		this.menuList = menuList;
		this.root = new BaseMenu();
	}

	public Tree getTreeJson() {
		this.root.setId("0");
		this.root.setLeaf(0);
		this.root.setExpanded(0);
		return this.getNodeJson(this.menuList, this.root);
	}

	private Tree getNodeJson(List<BaseMenu> list, BaseMenu node) {
		Tree tree = new Tree();
		tree.setId("_authority_" + node.getId());
		tree.setText(node.getMenuName());
		tree.setIconCls(node.getIconCss());
//		tree.setGlyph(node.getGlyph());
		tree.setChildren(new ArrayList<Tree>());
		if (list == null) {
			return tree;
		}

		if (hasChild(list, node)) {
			List<Tree> childTree = new ArrayList<Tree>();
			tree.setUrl("");
			tree.setLeaf(node.getLeaf() == 1 ? true : false);
			tree.setExpanded(node.getExpanded() == 1 ? true : false);
			List<BaseMenu> childList = getChildList(list, node);
			Iterator<BaseMenu> iterator = childList.iterator();
			while (iterator.hasNext()) {
				childTree.add(getNodeJson(list, iterator.next()));
			}
			tree.setChildren(childTree);
		} else {
			tree.setUrl(node.getMenuUrl());
			tree.setLeaf(node.getLeaf() == 1 ? true : false);
			tree.setExpanded(node.getExpanded() == 1 ? true : false);
		}
		return tree;
	}

	private boolean hasChild(List<BaseMenu> list, BaseMenu node) {
		return getChildList(list, node).size() > 0 ? true : false;
	}

	private List<BaseMenu> getChildList(List<BaseMenu> list, BaseMenu node) {
		Iterator<BaseMenu> iterator = list.iterator();
		List<BaseMenu> results = new ArrayList<BaseMenu>();
		while (iterator.hasNext()) {
			BaseMenu next = iterator.next();
			if (next.getParentId().equals(node.getId())) {
				results.add(next);
			}
		}
		return results;
	}

}
